<template>
  <div class="login-container">
    <img
      v-if="isShowLogo"
      src="@/assets/images/login_logo.png"
      class="logo"
      alt=""
    />
    <div class="login_wrap">
      <!-- <img class="login_img" src="@/assets/images/login_img.png" alt=""> -->
      <!-- <el-button type="primary" @click="sss">测试按钮</el-button> -->
      <div class="login_img">
        <div class="h3">{{ $t("message.login1") }}</div>
        <div class="text">{{ $t("message.login2") }}</div>
      </div>
      <div class="form_wrap" :class="$i18n.locale === 'RU' ? 'ey' : ''">
        <h3 class="title">{{ title }}</h3>
        <div v-if="!isShop" class="df_ac">
          <div class="label">{{ $t("message.shh") }}</div>
          <div class="line">
            <el-input
              v-model="shopId"
              :placeholder="$t('message.qsr') + $t('message.shbm')"
              type="text"
              tabindex="1"
            />
          </div>
        </div>
        <div class="df_ac">
          <div class="label">{{ $t("message.yhm") }}</div>
          <div class="line">
            <el-input
              v-model="loginForm.username"
              :placeholder="$t('message.qsr') + $t('message.zh')"
              type="text"
              tabindex="1"
            />
          </div>
        </div>
        <div class="df_ac">
          <div class="label">{{ $t("message.password") }}</div>
          <div class="line">
            <el-input
              v-model="loginForm.password"
              :placeholder="$t('message.qsr') + $t('message.password')"
              show-password
              type="password"
              tabindex="1"
              @keyup.enter.native="handleLogin"
            />
          </div>
        </div>
        <div class="df_ac">
          <div class="label">{{ $t("message.yzm") }}</div>
          <div class="line">
            <el-input
              v-model="loginForm.codeImage"
              :placeholder="$t('message.qsr') + $t('message.yzm')"
              @keyup.enter.native="handleLogin"
            />
            <img
              class="code_image"
              :src="codeImage"
              alt=""
              @click="refreshCodeImage"
            />
          </div>
        </div>

        <el-button
          v-preventReClick
          :loading="loading"
          type="primary"
          class="login_btn"
          @click.native.prevent="handleLogin"
          >{{ $t("message.ljdl") }}</el-button
        >

        <div class="line forget primaryColor mt10">
          <el-checkbox v-model="isRemPsd">
            <span
              style="font-size: 13px; font-weight: 400"
              class="placeholder9"
              >{{ $t("message.jzmm") }}</span
            >
          </el-checkbox>
          <el-dropdown class="avatar-container" trigger="click">
            <div class="avatar-wrapper">
              <span>{{ fhname($i18n.locale) }}</span>
              <i class="el-icon-caret-bottom" style="margin-top: 10px" />
            </div>
            <el-dropdown-menu slot="dropdown" class="user-dropdown">
              <el-dropdown-item
                v-for="item in langList"
                :key="item.id"
                @click.native="changeLanguage(item.code)"
              >
                <span style="display: block">{{ item.name }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="google">
          <img src="@/assets/images/ic_google.png" class="img" alt="" />
          <span class="placeholder6">{{ $t("message.login3") }}</span>
        </div>
      </div>
    </div>
    <div class="login_bottom">
      <div>
        ——
        <span v-if="isShowLogo">{{ $t("message.dmtt") }} ，</span
        >{{ $t("message.login4") }} ——
      </div>
      <div class="copyright">
        Copyright © 2022 - 2023
        <span v-if="isShowLogo">{{ $t("message.dmtt") }} .</span> All Rights
        Reserved. {{ $t("message.bqsy") }}
      </div>
    </div>

    <el-dialog
      :title="$t('message.xgmm')"
      :visible.sync="showPsdEdit"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :show-close="false"
      width="600"
    >
      <div>
        <div class="warnningTip">
          {{ $t("message.wjmmbt") }}
        </div>
        <el-form
          ref="psd_form"
          :model="psdForm"
          :rules="rules"
          label-width="auto"
          label-suffix="："
        >
          <el-form-item :label="$t('message.srjmm')" prop="oldPassword">
            <el-input
              v-model="psdForm.oldPassword"
              :placeholder="$t('message.qsrjmm')"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item :label="$t('message.srxmm')" prop="newPassword">
            <el-input
              v-model="psdForm.newPassword"
              :placeholder="$t('message.qsrxmm')"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item :label="$t('message.qrxmm')" prop="confirmPassword">
            <el-input
              v-model="psdForm.confirmPassword"
              :placeholder="$t('message.qsr') + $t('message.password')"
              type="password"
              show-password
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" @click="submitPsd">{{
          $t("message.qd")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  codeImageUrl,
  login,
  configDictionaries,
  motifyPwd,
  getGrayscaleVersion,
  getLang,
} from "@/api";
import { gray_path } from "./config";
import store from "@/store";
import i18n from "@/utils/i18n";
export default {
  name: "Login",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.psdForm.newPassword !== value) {
        callback(new Error(i18n.t("message.lcbyy")));
      } else {
        callback();
      }
    };
    return {
      isShowLogo: false,
      title: this.$t("message.dlcgd"),
      showForm: false,
      loginForm: {
        username: "",
        password: "",
        codeImage: "",
      },
      gray_path,
      shopId: "",
      isShop: "",
      loading: false,
      isRemPsd: false,
      passwordType: "password",
      redirect: undefined,
      langList: [],
      codeImage: codeImageUrl + "?time=" + new Date().getTime(),
      modalDialog: this.$store.getters.dialog,
      showPsdEdit: false,
      psdForm: {},
      rules: {
        oldPassword: [
          {
            required: true,
            message: this.$t("message.ymmbn"),
            trigger: "blur",
          },
        ],
        newPassword: [
          {
            required: true,
            message: this.$t("message.xmmbn"),
            trigger: "blur",
          },
          {
            min: 8,
            max: 20,
            message: this.$t("message.zfcd"),
            trigger: "blur",
          },
          {
            pattern:
              /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,20}$/,
            message: this.$t("message.xbhszzmts"),
            trigger: "blur",
          },
        ],
        confirmPassword: [
          {
            required: true,
            message: this.$t("message.qrmmbn"),
            trigger: "blur",
          },
          { required: true, validator: equalToPassword, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    let shopId =
      this.$route.query.shopId || localStorage.getItem("shopId") || "";
    const isShop = process.env.VUE_APP_ISSHOP || "";
    if (isShop) {
      this.isShop = isShop;
      this.shopId = isShop;
      shopId = isShop;
    } else {
      if (!shopId || shopId === "null") {
        shopId = "";
      }
      this.shopId = shopId;
    }
    localStorage.setItem("shopId", shopId);
    this.getLang();
    if (this.shopId) {
      setTimeout(() => {
        this.initInfo();
      }, 300);
    }
    this.$nextTick(() => {
      this.codeImage = codeImageUrl + "?time=" + new Date().getTime();
    });
  },
  mounted() {
    const username = localStorage.getItem("username") || "";
    const password = localStorage.getItem("password") || "";
    const isRemPsd = localStorage.getItem("isRemPsd") || false;
    if (password) {
      this.loginForm.username = username;
      this.loginForm.password = password;
    }
    this.isRemPsd = JSON.parse(isRemPsd);
    this.showForm = true;
    // if (this.$route.query.shopId) {
    //   localStorage.setItem('shopId', this.$route.query.shopId)
    // } else {
    //   // this.queryURLParams()
    // }
    if (this.$route.query.venueId)
      sessionStorage.setItem("venueId", this.$route.query.venueId);
  },
  methods: {
    // sss () {
    //   console.log('4444')
    //   if (window.Android) {
    //     let arr = {
    //       showAvatar: 'show',
    //       nickName: 'name'
    //     }
    //     let json = JSON.stringify(arr)
    //     alert(json)
    //     Android.setMember(json)
    //   }
    // },
    getLang() {
      getLang({
        param: {},
      })
        .then((res) => {
          this.langList = res.record.languageTypeResponses;
        })
        .catch(() => {});
    },
    changeLanguage(lang) {
      this.$i18n.locale = lang; // 切换语言
      localStorage.setItem("language", lang);
      if (window.Android) {
        Android.setLanguage(lang);
        Android.refreshWebView();
      }
      window.location.reload();
    },
    fhname(s) {
      const arr = [...this.langList];
      let name = "";
      arr.forEach((e) => {
        if (s === e.code) {
          name = e.name;
        }
      });
      return name;
    },
    submitPsd() {
      this.$refs.psd_form.validate((valid) => {
        if (valid) {
          motifyPwd({
            param: {
              userId: sessionStorage.getItem("userId"),
              oldpassword: this.psdForm.oldPassword,
              newpassword: this.psdForm.confirmPassword,
            },
          })
            .then((res) => {
              if (res.errorCode !== "000000") return;
              const { gray_path } = this;
              sessionStorage.setItem("isLogin", true);
              this.$message.success(this.$t("message.mmxgcg"));
              // this.$store.dispatch('routes/changeRoutes')
              getGrayscaleVersion({
                param: { shopId: this.shopId, isCheckShop: 0 },
              }).then((grayRes) => {
                if (
                  grayRes.record.versionType &&
                  grayRes.record.versionType === "1"
                ) {
                  if (gray_path.indexOf("_gray") > -1) {
                    location.assign(this.gray_path + "/#/venueList");
                  } else {
                    location.assign(this.gray_path + "_gray/#/venueList");
                  }
                  // location.assign(this.gray_path + '_gray/#/venueList')
                } else {
                  if (gray_path.indexOf("_gray") > -1) {
                    location.assign(
                      gray_path.replace("_gray", "") + "/#/venueList"
                    );
                  } else {
                    location.assign(this.gray_path + "/#/venueList");
                  }
                }
              });
              // this.$router.push({ path: '/venueList' })
            })
            .catch(() => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    queryURLParams() {
      const bm = "xxxxx";
      const strNum = bm.length;
      const indexStart = window.location.href.indexOf(bm) + strNum;
      const str = window.location.href.substring(indexStart);
      const indexEnd =
        str.indexOf("/") + window.location.href.indexOf(bm) + strNum;
      const shopId = window.location.href.substring(indexStart, indexEnd);
      localStorage.setItem("shopId", shopId);
    },
    initInfo() {
      configDictionaries({ param: { codes: "LOGIN_MENU_TITLE" } }).then(
        (res) => {
          if (res.errorCode !== "000000") return;
          if (res.recordList && res.recordList.length > 0) {
            res.recordList.map((item) => {
              if (
                item &&
                item.code === "LOGIN_MENU_TITLE" &&
                item.val !== "1"
              ) {
                this.isShowLogo = true;
                this.title = this.$t("message.dldmcgd");
              }
            });
          }
          this.refreshCodeImage();
        }
      );
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    refreshCodeImage() {
      this.codeImage = codeImageUrl + "?time=" + new Date().getTime();
    },
    handleLogin() {
      const { username, password, codeImage } = this.loginForm;
      const that = this;
      if (!this.shopId) {
        return this.$message.error(
          this.$t("message.qsr") + this.$t("message.shbm")
        );
      }
      if (!username) {
        return this.$message.error(
          this.$t("message.qsr") + this.$t("message.yhm")
        );
      }
      if (!password) {
        return this.$message.error(
          this.$t("message.qsr") + this.$t("message.password")
        );
      }
      if (!codeImage) {
        return this.$message.error(
          this.$t("message.qsr") + this.$t("message.yzm")
        );
      }
      localStorage.setItem("shopId", this.shopId);
      that.loading = true;
      login({
        param: {
          userName: username.trim(),
          password: password,
          imgCode: codeImage,
        },
      })
        .then((res) => {
          const { gray_path } = this;
          that.loading = false;
          if (res.errorCode !== "000000") return;
          if (this.isRemPsd) {
            localStorage.setItem("username", username);
            localStorage.setItem("password", password);
            localStorage.setItem("isRemPsd", this.isRemPsd);
          } else {
            localStorage.removeItem("username");
            localStorage.removeItem("password");
            localStorage.removeItem("isRemPsd");
          }
          that.$store.dispatch("user/login", res.record);
          // that.$router.push(`/venueList`)
          // return false
          if (res.record.editPwd === "1") {
            this.pwdTip(this.$t("message.mmsjtc"));
            getGrayscaleVersion({
              param: { shopId: this.shopId, isCheckShop: 0 },
            }).then((grayRes) => {
              if (
                grayRes.record.versionType &&
                grayRes.record.versionType === "1"
              ) {
                if (gray_path.indexOf("_gray") > -1) {
                  location.assign(this.gray_path + "/#/venueList");
                } else {
                  location.assign(this.gray_path + "_gray/#/venueList");
                }
                // location.assign(this.gray_path + '_gray/#/venueList')
              } else {
                if (gray_path.indexOf("_gray") > -1) {
                  location.assign(
                    gray_path.replace("_gray", "") + "/#/venueList"
                  );
                } else {
                  location.assign(this.gray_path + "/#/venueList");
                }
              }
            });
          } else if (res.record.editPwd === "2") {
            this.showPsdEdit = true;
          } else {
            getGrayscaleVersion({
              param: { shopId: this.shopId, isCheckShop: 0 },
            }).then((grayRes) => {
              if (
                grayRes.record.versionType &&
                grayRes.record.versionType === "1"
              ) {
                if (gray_path.indexOf("_gray") > -1) {
                  location.assign(this.gray_path + "/#/venueList");
                } else {
                  location.assign(this.gray_path + "_gray/#/venueList");
                }
                // location.assign(this.gray_path + '_gray/#/venueList')
              } else {
                if (gray_path.indexOf("_gray") > -1) {
                  location.assign(
                    gray_path.replace("_gray", "") + "/#/venueList"
                  );
                } else {
                  location.assign(this.gray_path + "/#/venueList");
                }
              }
            });
            // this.$router.push({ path: '/venueList' })
          }
          // that.$router.push({ path: '/venueList' })
        })
        .catch(() => {
          that.loading = false;
          this.loginForm.codeImage = "";
          that.refreshCodeImage();
        });
    },
    pwdTip(txt) {
      this.$notify({
        title: this.$t("message.ts"),
        type: "warning",
        message: txt,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #cfe9ff;
  overflow: hidden;
  position: relative;
  background-image: url("../../assets/images/login_bg.png");
  background-size: 100% 100%;
  background-attachment: fixed;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  .login_wrap {
    width: 1000px;
    height: 600px;
    box-sizing: border-box;
    background: #ffffff;
    box-shadow: 0px 20px 60px 0px rgba(0, 0, 0, 0.11);
    display: flex;
    .login_img {
      width: 500px;
      height: 600px;
      background: url("../../assets/images/login_img.png");
      background-size: 100% 100%;
      padding-left: 40px;
      padding-top: 80px;
      .h3 {
        font-size: 28px;
        font-weight: 700;
        color: #fff;
        margin-bottom: 26px;
      }
      .text {
        font-size: 18px;
        color: #fff;
      }
    }
    .form_wrap {
      flex: 1;
      height: 100%;
      background-color: #fff;
      box-sizing: border-box;
      padding: 0 80px;
      position: relative;
      .title {
        font-size: 24px;
        margin-top: 70px;
        margin-bottom: 48px;
        text-align: center;
      }
      .label {
        color: #222222;
        margin-bottom: 18px;
        font-size: 14px;
        margin-right: 12px;
        width: 42px;
      }
      &.ey {
        .label {
          width: 135px;
        }
      }
      .line {
        margin-bottom: 20px;
        display: flex;
        width: 280px;
        .el-input {
          height: 40px;
          // font-size: 14px;
          ::v-deep .el-input__inner {
            height: 40px !important;
          }
        }
        .code_image {
          width: 100px;
          margin-left: 10px;
        }
      }
      .forget {
        justify-content: space-between;
        width: 100%;
        .text {
          cursor: pointer;
        }
      }
      .login_btn {
        width: 100%;
        height: 40px;
        background: linear-gradient(90deg, #435ebe 0%, #4f7bdf 100%);
        box-shadow: 0px 2px 8px 0px rgba(67, 94, 190, 0.15);
        border-radius: 2px;
        margin: 0 auto;
      }
      .agreement {
        text-align: center;
      }
      .google {
        position: absolute;
        left: 50%;
        transform: translate(-50%, 0);
        bottom: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        font-size: 12px;
        .img {
          margin-right: 5px;
          width: 18px;
        }
      }
    }
  }
  .logo {
    position: absolute;
    top: 4%;
    left: 5.6%;
    width: 200px;
  }
  .login_bottom {
    text-align: center;
    position: absolute;
    bottom: 3%;
    left: 50%;
    transform: translate(-50%, 0);
    font-size: 14px;
    .copyright {
      color: #828d9e;
      margin-top: 2.5%;
      font-size: 12px;
    }
  }
}
</style>
